// pages/payinfo/payinfo.js
var util = require('../../utils/util')
Page({

  /**
   * 页面的初始数据
   */
  data: {
    good: {
      imgSrc: '',
      name: "",
      title: ["白色;", "规格1"],
      price: 120,
      count: 1,
      time: '',
      type: 0
    },
    goods: [],
    user: {},
    total: '0.00',
    account: '0.00',
    // 运费
    fare: '0.00',
  },

  // 获取默认地址
  getDefaultAddress() {
    console.log('1');
    wx.cloud.database().collection('location_list')
      .where({
        state: true
      })
      .get()
      .then(res => {
        this.setData({
          user: res.data[0]
        })
        wx.setStorageSync('id', res.data[0]._id)
      })
      .catch(err => {
        console.error('获取失败', err);
      })
  },
  // 获取地址
  getAddress() {
    let local_id = wx.getStorageSync('id')
    wx.cloud.database().collection('location_list')
      .doc(local_id)
      .get()
      .then(res => {
        this.setData({
          user: res.data
        })
      })
      .catch(err => {
        console.error('获取失败', err);
      })
  },
  goToAddressInfo() {
    wx.navigateTo({
      url: '/pages/addressinfo/addressinfo',
    })
  },
  goShowInfo() {
    let data = {
      total: this.data.total,
      account: this.data.account,
      fare: this.data.fare
    }
    var time = util.formatTime(new Date());
    wx.setStorageSync('price', data)
    wx.navigateTo({
      url: '/pages/showInfo/showInfo?time=' + time
    })
    let order = this.data.goods
    let db = wx.cloud.database()
    const _ = db.command
    db.collection('orderList').add({
      data: {
        myOrder: [],
        price: [],
        state: '待发货',
        time: time
      }
    }).then(res => {
      console.log(res._id)
      db.collection('orderList').doc(res._id).update({
          data: {
            myOrder: _.push(order),
            price: _.push(data),
          }
        })
        .then(e => {
          console.log('插入成功', e)
        })
        .catch(r => {
          console.log('插入失败', r)
        })

      //增加销售量
      wx.cloud.callFunction({
          name: 'addSale',
          data: {
            type: this.data.type,
            order:order
          },
        })
        .then(res => {
          console.log(res.result)
        })
        .catch(console.error)
    }).catch(err => {
      console.error(err)
    })

  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.setData({
      total: (parseFloat(options.total)).toFixed(2),
      type: options.type
    })
    this.getAccount()
    let goods = wx.getStorageSync('goods')
    this.setData({
      goods: goods
    })
  },
  // 合计
  getAccount() {
    this.setData({
      account: (parseFloat(this.data.total) + parseFloat(this.data.fare)).toFixed(2)
    })
  },
  onShow: function () {
    if (wx.getStorageSync('id')) {
      this.getAddress()
    } else {
      this.getDefaultAddress()
    }

  }
})